/*
 * Copyright (c) 2014 laidian. All Rights Reserved.
 * 
 * @author yaoyuming
 * 
 * @date 2020/9/1 0001
 */
package com.yao.auth.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.yao.auth.entity.dto.UserDto;
import com.yao.auth.service.LoginService;
import com.yao.common.util.ThrowUtils;
import com.yao.sys.mapper.UserMapper;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 实现用户登陆校验
 * 
 * @author yaoyuming
 * @date 2020/9/1 0001 14:18
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper mapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("登陆用户名:{}",username);

        if(StrUtil.isEmpty(username)){
            throw new UsernameNotFoundException("用户登陆service没接收到用户名.");
        }

        UserDto user = ThrowUtils.isNull(mapper.findByUsername(username), "用户名不存在.");

        log.debug("用户[{}]，拥有的权限{}", user, user.getRoles());
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // todo 登陆逻辑在这里补充，token生成，redis缓存等.


        return user;
    }
}